package com.byx.chatclient.view.activity.main;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.byx.chatclient.ChatApp;
import com.byx.chatclient.R;
import com.byx.chatclient.bean.PopupMenuItem;
import com.byx.chatclient.entity.message.Message;
import com.byx.chatclient.event.EventType;
import com.byx.chatclient.event.MessageEvent;
import com.byx.chatclient.im.MessageConverter;
import com.byx.chatclient.im.MessageNotification;
import com.byx.chatclient.service.NettyService;
import com.byx.chatclient.utils.GlideUtils;
import com.byx.chatclient.utils.GradientStatusBarUtil;
import com.byx.chatclient.utils.SoftInputUtil;
import com.byx.chatclient.view.activity.CreateGroupActivity;
import com.byx.chatclient.view.activity.SearchActivity;
import com.byx.chatclient.widget.PopupMenu;
import com.byx.chatclient.widget.Toolbar;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author Superb
 */
public class MainActivity extends AppCompatActivity {
//    @BindView(R.id.viewPager)
//    protected ViewPager viewPager;
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String MENU_BUILDER = "MenuBuilder";

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.toolbar)
    protected Toolbar mToolbar;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.ll_search_view)
    protected LinearLayout mLlSearchView;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.ll_container)
    protected LinearLayout mLlContainer;
//    @SuppressLint("NonConstantResourceId")
//    @BindView(R.id.tv_search_cancel)
    protected TextView mTvCancel;
    protected EditText mEtSearch;

    private NettyService nettyService;

    private final ServiceConnection connection = new ServiceConnection();
    private Intent intent;
    private Unbinder mUnbinder;

    private boolean inSearchView;
    private static MainActivity activity;

    @SuppressLint({"NonConstantResourceId", "ClickableViewAccessibility"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mUnbinder = ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        GradientStatusBarUtil.getInstance().bind(this).withBackgroundResource(R.drawable.toolbar).init();

        initService();
        mTvCancel = mLlSearchView.findViewById(R.id.tv_search_cancel);
        mTvCancel.setOnClickListener(v -> hideSearchView());
        mEtSearch = mLlSearchView.findViewById(R.id.et_search);
        mLlSearchView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (v != mEtSearch){
                        SoftInputUtil.hideSoftInput(mEtSearch);
                        mEtSearch.clearFocus();
                    }
                    return false;
                }
                // 必不可少，否则所有的组件都不会有TouchEvent了
                if (getWindow().superDispatchTouchEvent(event)) {
                    return true;
                }
                return onTouchEvent(event);
            }
        });


        mToolbar.setOverflowIcon(AppCompatResources.getDrawable(this,R.mipmap.ic_menu_add));
        mToolbar.setOnPopupMenuListener(new Toolbar.OnPopupMenuListener() {
            @Override
            public PopupMenu initMenu() {
                PopupMenu menu = new PopupMenu(MainActivity.this);
                menu.setWidth(500)
                        .addMenuItem(new PopupMenuItem(AppCompatResources.getDrawable(MainActivity.this,R.mipmap.ic_create_group_64),"发起群聊"))
                        .addMenuItem(new PopupMenuItem(AppCompatResources.getDrawable(MainActivity.this,R.mipmap.ic_add_friend_gray_64),"加好友/群"))
//                        .setLocation(mToolbar,-1,0)
                ;
                return menu;
            }

            @Override
            public void onMenuOpened() {
//                Toast.makeText(MainActivity.this,"打开菜单",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onMenuItemClick(int position) {
                switch (position){
                    case 0:
                        startActivity(new Intent(MainActivity.this, CreateGroupActivity.class));
                        break;
                    case 1:
                        startActivity(new Intent(MainActivity.this, SearchActivity.class));
                        Toast.makeText(MainActivity.this,"添加好友或群",Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                    default:
                        break;
                }
            }

            @Override
            public void onMenuClosed() {
//                Toast.makeText(MainActivity.this,"关闭了",Toast.LENGTH_SHORT).show();
            }
        });
        mToolbar.setNavigationIcon(ChatApp.getInstance().getUserPo().getLocalAvatarUrl());
        mToolbar.setSubTitleVisibility(View.GONE);
        setSupportActionBar(mToolbar);

//        getSupportActionBar().setDisplayShowTitleEnabled(false);

        final BottomNavigationView navView = findViewById(R.id.nav_view);
//        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);

//        navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
//            @Override
//            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//                switch (item.getItemId()){
//                    case R.id.navigation_home:
//                        viewPager.setCurrentItem(0);
//                        break;
//                    case R.id.navigation_dashboard:
//                        viewPager.setCurrentItem(1);
//                        break;
//                    case R.id.navigation_notifications:
//                        viewPager.setCurrentItem(2);
//                        break;
//                    default:break;
//                }
//                return false;
//            }
//        });

//        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                navView.getMenu().getItem(position).setChecked(true);
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });

//        ViewPagerFragmentAdapter adapter=new ViewPagerFragmentAdapter(getSupportFragmentManager(),FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
//        adapter.addFragment(new HomeFragment());
//        adapter.addFragment(new ContactPersonFragment());
//        adapter.addFragment(new MineFragment());
//        viewPager.setAdapter(adapter);
//        viewPager.setOffscreenPageLimit(3);

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
//        navController.
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);

        activity = this;
    }

    public Toolbar getToolbar(){
        return mToolbar;
    }

    public void hideToolbarMenu(){
        mToolbar.setMenuButtonVisibility(View.GONE);
    }

    public void showToolbarMenu(){
        mToolbar.setMenuButtonVisibility(View.VISIBLE);
    }

    public void hideToolbarAvatar(){
        mToolbar.setAvatarVisibility(View.GONE);
    }

    public void showToolbarAvatar(){
        mToolbar.setAvatarVisibility(View.VISIBLE);
    }

    public void showSearchView(){
        mLlSearchView.setVisibility(View.VISIBLE);
        mLlContainer.setVisibility(View.GONE);
        SoftInputUtil.showSoftInput(this,mEtSearch);
        inSearchView = true;
    }

    public void hideSearchView(){
        SoftInputUtil.hideSoftInput(this,mEtSearch);
        mLlContainer.setVisibility(View.VISIBLE);
        mLlSearchView.setVisibility(View.GONE);
        inSearchView = false;
    }

    private void setBackgroundAlpha(float f) {
        WindowManager.LayoutParams layoutParams=MainActivity.this.getWindow().getAttributes();
        layoutParams.alpha=f;
        MainActivity.this.getWindow().setAttributes(layoutParams);
    }

    private void initService() {
        intent = new Intent(this, NettyService.class);
        bindService(intent, connection,BIND_AUTO_CREATE);
    }

    @Override
    public void onBackPressed() {
        if (inSearchView){
            hideSearchView();
        }else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
        }
    }

    @Override
    protected void onDestroy() {
        activity = null;
        super.onDestroy();
        mUnbinder.unbind();
        GradientStatusBarUtil.getInstance().unbind();
        EventBus.getDefault().unregister(this);
        unbindService(connection);
        stopService(intent);
    }

    /**
     * UI线程更新消息
     * @param event 携带消息数据的事件
     */
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEvent(MessageEvent event){
        switch (event.getEventType()){
            case SINGLE_CHAT_MSG:
                Message singleChatMessage = (Message) event.getData();
                if (ChatApp.getInstance().isRunningInBackground()){
                    MessageNotification.notification(MainActivity.this,singleChatMessage,true);
                }
                nettyService.saveMessage(MessageConverter.toMessagePo(singleChatMessage, true));
                break;
            case GROUP_CHAT_MSG:
                Message groupChatMessage = (Message) event.getData();
                if (ChatApp.getInstance().isRunningInBackground()){
                    MessageNotification.notification(MainActivity.this,groupChatMessage,false);
                }
                nettyService.saveMessage(MessageConverter.toMessagePo(groupChatMessage, false));
                break;
            case AVATAR_CHANGED:
                mToolbar.setNavigationIcon(ChatApp.getInstance().getUserPo().getLocalAvatarUrl());
                break;
            case ADD_FRIEND_MSG:
            case UPLOAD_COMPLETE:
            case DOWNLOAD_COMPLETE:
            default:
                break;
        }
    }

    class ServiceConnection implements android.content.ServiceConnection {

        /**
         * Called when a connection to the Service has been established, with
         * the {@link IBinder} of the communication channel to the
         * Service.
         *
         * <p class="note"><b>Note:</b> If the system has started to bind your
         * client app to a service, it's possible that your app will never receive
         * this callback. Your app won't receive a callback if there's an issue with
         * the service, such as the service crashing while being created.
         *
         * @param name    The concrete component name of the service that has
         *                been connected.
         * @param service The IBinder of the Service's communication channel,
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            nettyService= ((NettyService.NettyServiceBinder) service).getInstance();
        }

        /**
         * Called when a connection to the Service has been lost.  This typically
         * happens when the process hosting the service has crashed or been killed.
         * This does <em>not</em> remove the ServiceConnection itself -- this
         * binding to the service will remain active, and you will receive a call
         * to {@link #onServiceConnected} when the Service is next running.
         *
         * @param name The concrete component name of the service whose
         *             connection has been lost.
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    public static void finishSelf(){
        activity.finish();
    }
}